package com.hsu.apibackend.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hsu.apibackend.annotation.AuthCheck;
import com.hsu.apibackend.common.*;
import com.hsu.apibackend.constant.CommonConstant;
import com.hsu.apibackend.exception.BusinessException;
import com.hsu.apibackend.model.dto.interfaceinfo.*;
import com.hsu.apibackend.model.entity.User;
import com.hsu.apibackend.model.enums.InterfaceStatusEnum;
import com.hsu.apibackend.model.vo.UserVO;
import com.hsu.apibackend.service.InterfaceInfoService;
import com.hsu.apibackend.service.UserService;
import com.hsu.apicommon.model.entity.InterfaceInfo;
import icu.hsu.apisdk.client.HsuApiClient;
import icu.hsu.apisdk.model.request.CurrencyRequest;
import icu.hsu.apisdk.model.response.ResultResponse;
import icu.hsu.apisdk.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hsu.apibackend.constant.UserConstant.ADMIN_ROLE;

/**
 * 接口信息接口
 * @Author Hsu琛君珩
 * @Date 2024-09-10 14:31
 * @Description
 * @Version: v1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/interfaceInfo")
public class InterfaceInfoController {
    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Resource
    private ApiService apiService;

    private final Gson gson = new Gson();

    // region 增删改查

    /**
     * 添加接口信息
     *
     * @param interfaceInfoAddRequest 接口信息添加请求对象
     * @param request                 HTTP 请求对象
     * @return {@link BaseResponse}<{@link Long}> 新增的接口信息 ID
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        // 请求参数校验
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建 InterfaceInfo 对象并填充数据
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        if (CollectionUtils.isNotEmpty(interfaceInfoAddRequest.getRequestParams())) {
            List<RequestParamsField> requestParamsFields = interfaceInfoAddRequest.getRequestParams().stream()
                    .filter(field -> StringUtils.isNotBlank(field.getFieldName()))
                    .collect(Collectors.toList());
            String requestParams = JSONUtil.toJsonStr(requestParamsFields);
            interfaceInfo.setRequestParams(requestParams);
        }

        if (CollectionUtils.isNotEmpty(interfaceInfoAddRequest.getResponseParams())) {
            List<ResponseParamsField> responseParamsFields = interfaceInfoAddRequest.getResponseParams().stream()
                    .filter(field -> StringUtils.isNotBlank(field.getFieldName()))
                    .collect(Collectors.toList());
            String responseParams = JSONUtil.toJsonStr(responseParamsFields);
            interfaceInfo.setResponseParams(responseParams);
        }

        // 复制请求属性到接口信息对象
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);

        // 校验接口信息数据
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);

        // 获取当前登录用户
        UserVO loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());

        // 保存接口信息
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        // 返回新创建的接口信息 ID
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除接口信息
     *
     * @param deleteRequest 删除请求对象，包含要删除的接口ID
     * @param request       HTTP请求对象，用于获取当前登录用户信息
     * @return {@link BaseResponse}<{@link Boolean}> 返回删除结果，true为删除成功，false为删除失败
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 校验请求参数是否为空，且ID必须大于0
        if (ObjectUtils.anyNull(deleteRequest, deleteRequest.getId()) || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 获取当前登录用户信息
        UserVO user = userService.getLoginUser(request);
        long id = deleteRequest.getId();

        // 判断接口信息是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 校验权限，仅允许本人或管理员删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 删除接口信息
        boolean isDeleted = interfaceInfoService.removeById(id);
        return ResultUtils.success(isDeleted);
    }

    /**
     * 更新接口头像URL
     *
     * @param request                          HTTP请求对象，用于获取当前登录用户信息
     * @param interfaceInfoUpdateAvatarRequest 更新头像请求对象，包含接口ID和新的头像URL
     * @return {@link BaseResponse}<{@link Boolean}> 返回更新结果，true为更新成功，false为更新失败
     */
    @PostMapping("/updateInterfaceInfoAvatar")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfoAvatarUrl(@RequestBody InterfaceInfoUpdateAvatarRequest interfaceInfoUpdateAvatarRequest,
                                                              HttpServletRequest request) {
        // 校验请求参数是否为空，且ID必须大于0
        if (ObjectUtils.anyNull(interfaceInfoUpdateAvatarRequest, interfaceInfoUpdateAvatarRequest.getId()) || interfaceInfoUpdateAvatarRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建InterfaceInfo对象并将请求中的属性复制到该对象中
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateAvatarRequest, interfaceInfo);

        // 更新接口信息并返回更新结果
        boolean updateResult = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(updateResult);
    }

    /**
     * 更新接口信息
     *
     * @param interfaceInfoUpdateRequest 接口信息更新请求对象，包含更新的字段
     * @param request                    HTTP请求对象，用于获取当前登录用户信息
     * @return {@link BaseResponse}<{@link Boolean}> 返回更新结果，true为更新成功，false为更新失败
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = ADMIN_ROLE)
    @Transactional(rollbackFor = Exception.class) // 在事务中执行，若发生异常则回滚
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        // 校验请求参数是否为空，且ID必须大于0
        if (ObjectUtils.anyNull(interfaceInfoUpdateRequest, interfaceInfoUpdateRequest.getId()) || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建InterfaceInfo对象并处理请求参数和响应参数
        InterfaceInfo interfaceInfo = new InterfaceInfo();

        // 处理请求参数字段，确保非空字段被保存
        if (CollectionUtils.isNotEmpty(interfaceInfoUpdateRequest.getRequestParams())) {
            List<RequestParamsField> requestParamsFields = interfaceInfoUpdateRequest.getRequestParams().stream()
                    .filter(field -> StringUtils.isNotBlank(field.getFieldName()))
                    .collect(Collectors.toList());
            String requestParams = JSONUtil.toJsonStr(requestParamsFields);
            interfaceInfo.setRequestParams(requestParams);
        } else {
            interfaceInfo.setRequestParams("[]"); // 默认设置为空数组
        }

        // 处理响应参数字段，确保非空字段被保存
        if (CollectionUtils.isNotEmpty(interfaceInfoUpdateRequest.getResponseParams())) {
            List<ResponseParamsField> responseParamsFields = interfaceInfoUpdateRequest.getResponseParams().stream()
                    .filter(field -> StringUtils.isNotBlank(field.getFieldName()))
                    .collect(Collectors.toList());
            String responseParams = JSONUtil.toJsonStr(responseParamsFields);
            interfaceInfo.setResponseParams(responseParams);
        } else {
            interfaceInfo.setResponseParams("[]"); // 默认设置为空数组
        }

        // 将请求中的更新信息复制到InterfaceInfo对象中
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);

        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);

        // 获取当前登录用户
        UserVO user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();

        // 判断接口信息是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 仅允许管理员或接口信息的创建者修改
        if (!userService.isAdmin(request) && !oldInterfaceInfo.getUserId().equals(user.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        // 更新接口信息并返回更新结果
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 通过id获取接口信息
     *
     * @param id 接口信息的唯一标识符
     * @return {@link BaseResponse}<{@link InterfaceInfo}> 返回包含接口信息的响应体
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(@RequestParam("id") long id) {
        // 校验 id 是否有效
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "无效的接口ID");
        }

        // 通过 id 获取接口信息
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);

        // 判断是否查询到数据
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "接口信息未找到");
        }

        // 返回成功的响应体
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取接口信息列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest 接口信息查询请求对象
     * @return {@link BaseResponse}<{@link List}<{@link InterfaceInfo}>> 返回包含接口信息列表的响应体
     */
    @AuthCheck(mustRole = ADMIN_ROLE)
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        // 校验查询请求参数是否为空
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询请求参数不能为空");
        }

        // 将查询请求对象的属性复制到 InterfaceInfo 实体类中
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);

        // 构建查询条件
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);

        // 查询符合条件的接口信息列表
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);

        // 返回查询结果
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取接口信息列表
     *
     * @param interfaceInfoQueryRequest 接口信息查询请求对象
     * @param request 请求对象
     * @return {@link BaseResponse}<{@link Page}<{@link InterfaceInfo}>>
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        // 校验请求参数
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 将查询请求对象的属性复制到 InterfaceInfo 实体类中
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);

        // 分页大小、排序字段、排序顺序等参数
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        long current = interfaceInfoQueryRequest.getCurrent();

        // 其他查询条件
        String url = interfaceInfoQueryRequest.getUrl();
        String name = interfaceInfoQueryRequest.getName();
        String method = interfaceInfoQueryRequest.getMethod();
        String description = interfaceInfoQueryRequest.getDescription();
        Integer status = interfaceInfoQueryRequest.getStatus();
        Integer reduceScore = interfaceInfoQueryRequest.getReduceScore();
        String returnFormat = interfaceInfoQueryRequest.getReturnFormat();

        // 防止分页大小过大（限制爬虫行为）
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页大小超过限制");
        }

        // 构建查询条件
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(description)) {
            queryWrapper.and(qw -> qw.like("name", name).or().like("description", description));
        }
        queryWrapper
                .like(StringUtils.isNotBlank(url), "url", url)
                .like(StringUtils.isNotBlank(returnFormat), "returnFormat", returnFormat)
                .eq(StringUtils.isNotBlank(method), "method", method)
                .eq(ObjectUtils.isNotEmpty(status), "status", status)
                .eq(ObjectUtils.isNotEmpty(reduceScore), "reduceScore", reduceScore);

        // 按指定字段排序
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        // 分页查询
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);

        // 获取当前用户，并判断是否为管理员
        User user = userService.isTourist(request);
        if (user == null || !ADMIN_ROLE.equals(user.getUserRole())) {
            // 非管理员用户只能查看已上线的接口信息
            List<InterfaceInfo> filteredList = interfaceInfoPage.getRecords().stream()
                    .filter(interfaceInfo -> interfaceInfo.getStatus().equals(InterfaceStatusEnum.ONLINE.getValue()))
                    .collect(Collectors.toList());
            interfaceInfoPage.setRecords(filteredList);
        }

        // 返回分页结果
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 按搜索文本页查询数据
     *
     * @param interfaceInfoQueryRequest 接口信息查询请求
     * @param request                   请求对象
     * @return {@link BaseResponse}<{@link Page}<{@link InterfaceInfo}>>
     */
    @GetMapping("/get/searchText")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoBySearchTextPage(InterfaceInfoSearchTextRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        // 参数校验：如果请求参数为空，则抛出异常
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 将请求参数拷贝到查询对象
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);

        // 从请求参数中提取搜索文本、分页大小、当前页、排序字段和排序顺序
        String searchText = interfaceInfoQueryRequest.getSearchText();
        long size = interfaceInfoQueryRequest.getPageSize();
        long current = interfaceInfoQueryRequest.getCurrent();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();

        // 创建查询条件包装器
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        // 如果搜索文本不为空，则根据名称和描述进行模糊匹配
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like(StringUtils.isNotBlank(searchText), "name", searchText)
                    .or()
                    .like(StringUtils.isNotBlank(searchText), "description", searchText));
        }
        // 根据指定的排序字段和顺序进行排序
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        // 执行分页查询
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);

        // 如果当前用户不是管理员，则只能查看已上线的接口
        if (!userService.isAdmin(request)) {
            List<InterfaceInfo> interfaceInfoList = interfaceInfoPage.getRecords().stream()
                    .filter(interfaceInfo -> interfaceInfo.getStatus().equals(InterfaceStatusEnum.ONLINE.getValue()))
                    .collect(Collectors.toList());
            interfaceInfoPage.setRecords(interfaceInfoList);
        }

        // 返回查询结果
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 发布接口信息
     *
     * @param idRequest id请求对象，包含要上线的接口ID
     * @param request   请求对象
     * @return {@link BaseResponse}<{@link Boolean}> 返回是否成功发布
     */
    @AuthCheck(mustRole = ADMIN_ROLE) // 此操作仅限管理员权限
    @PostMapping("/online")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        // 参数校验：如果请求或ID为空，或者ID小于等于0，抛出参数错误异常
        if (ObjectUtils.anyNull(idRequest, idRequest.getId()) || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long id = idRequest.getId();

        // 根据ID从数据库中查询接口信息
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);

        // 如果接口信息不存在，抛出未找到错误
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 设置接口状态为 "已上线"
        interfaceInfo.setStatus(InterfaceStatusEnum.ONLINE.getValue());

        // 更新接口信息并返回操作结果
        return ResultUtils.success(interfaceInfoService.updateById(interfaceInfo));
    }

    /**
     * 下线接口信息
     *
     * @param idRequest id请求对象，包含要下线的接口ID
     * @param request   请求对象
     * @return {@link BaseResponse}<{@link Boolean}> 返回是否成功下线
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = ADMIN_ROLE) // 此操作仅限管理员权限
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        // 参数校验：检查请求或ID是否为空，或者ID是否小于等于0，若不合法抛出参数错误异常
        if (ObjectUtils.anyNull(idRequest, idRequest.getId()) || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long id = idRequest.getId();

        // 根据ID从数据库中获取接口信息
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);

        // 如果接口信息不存在，抛出未找到错误
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 将接口状态设置为 "已下线"
        interfaceInfo.setStatus(InterfaceStatusEnum.OFFLINE.getValue());

        // 更新接口信息，并返回操作结果
        return ResultUtils.success(interfaceInfoService.updateById(interfaceInfo));
    }

    // endregion

    /**
     * 调用指定接口
     *
     * @param invokeRequest 接口调用请求对象，包含接口ID及请求参数
     * @param request       请求对象，用于获取当前登录的用户信息
     * @return {@link BaseResponse}<{@link Object}> 返回接口调用结果
     */
    @PostMapping("/invoke")
    @Transactional(rollbackFor = Exception.class) // 如果发生异常，事务将回滚
    public BaseResponse<Object> invokeInterface(@RequestBody InvokeRequest invokeRequest, HttpServletRequest request) {
        // 校验请求参数和ID是否合法
        if (ObjectUtils.anyNull(invokeRequest, invokeRequest.getId()) || invokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long id = invokeRequest.getId();

        // 根据ID从数据库获取接口信息
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        // 检查接口是否已上线
        if (interfaceInfo.getStatus() != InterfaceStatusEnum.ONLINE.getValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口未开启");
        }

        // 构建请求参数，默认为空的JSON对象
        List<InvokeRequest.Field> fieldList = invokeRequest.getRequestParams();
        String requestParams = "{}";
        if (fieldList != null && !fieldList.isEmpty()) {
            JsonObject jsonObject = new JsonObject();
            for (InvokeRequest.Field field : fieldList) {
                jsonObject.addProperty(field.getFieldName(), field.getValue()); // 将每个参数的名称和值添加到JSON对象中
            }
            requestParams = gson.toJson(jsonObject); // 将JSON对象转换为字符串
        }

        // 将请求参数字符串转换为Map对象，便于后续传递参数
        Map<String, Object> params = new Gson().fromJson(requestParams, new TypeToken<Map<String, Object>>() {}.getType());

        // 获取当前登录用户的信息（包含AccessKey和SecretKey）
        UserVO loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();

        try {
            // 使用SDK创建API客户端，传入用户的AccessKey和SecretKey
            HsuApiClient hsuApiClient = new HsuApiClient(accessKey, secretKey);

            // 构建接口调用的请求对象
            CurrencyRequest currencyRequest = new CurrencyRequest();
            currencyRequest.setMethod(interfaceInfo.getMethod()); // 设置请求方法（GET、POST等）
            currencyRequest.setPath(interfaceInfo.getUrl()); // 设置请求URL
            currencyRequest.setRequestParams(params); // 设置请求参数

            // 调用API，并返回响应
            ResultResponse response = apiService.request(hsuApiClient, currencyRequest);
            return ResultUtils.success(response.getData()); // 返回调用结果
        } catch (Exception e) {
            // 如果调用过程中发生异常，抛出系统错误
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        }
    }

}
